<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</head>
<body>
    <h1>拦截器练习</h1>
    <input type="text" id="ipt">
    <button id="btn">提交</button>
    <script>
        let myaxios = axios.create({
            baseURL: '/',
            timeout: 10000,
            headers: {},
        })

        //添加请求拦截器
        myaxios.interceptors.request.use(config => {
        // Do something before request is sent
        //..设置token并让响应头携带token
        let token = "lkhsdalkhjflsa.asdasfadsfdasf.asfasfasdfasdf";
        config.headers.token = token
        //2.让进度条开始
        NProgress.start()
        return config;
        },error => {
        // Do something with request error
        return Promise.reject(error);
        });

        //添加响应拦截器
        myaxios.interceptors.response.use(response => {
        // Do something before response is sent
        //1.结束进度条
        NProgress.done()
        //2.对请求到的结果进行处理,只拿正确的信息,如果遇到错误的信息,直接给异常处理
        if (response.data.code!==10000) {
            return Promise.reject(response.data.msg);
        }
        return response.data.data;
        },error => {
        // Do something with response error
        return Promise.reject(error);
        });
        let ipt = document.querySelector('#ipt')
        let btn = document.querySelector('#btn')
        btn.onclick = async function(){
            try{
                let result = await myaxios.get('/user',{
                    params: {
                        userid: '001'
                    }
                })
                console.log(result);
            }
            catch(e){
                console.log(e,'出现错误');
            }
        }
    </script> 
</body>
</html>